package com.mall.db.service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mall.db.dao.SendMessageDao;
import com.mall.db.domain.Member;
import com.mall.db.domain.SendMessage;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wxd
 * @since 2021-09-16
 */
@Service
public class SendMessageService extends ServiceImpl<SendMessageDao, SendMessage>{

    @Resource(name = "memberService")
    private MemberService ms;

    public boolean batchSave(SendMessage sm) {

        List<SendMessage> sms = new ArrayList<>();
        List<String> acceptUsers = new ArrayList<>();

        //如果选择的是所有 all
        if ("all".equals(sm.getAcceptType())) {

            if ("member".equals(sm.getAccept())){
                List<Member> members =  ms.list();
                for (Member m : members){
                    acceptUsers.add(m.getLoginName());
                }

            }else {
                //TODO vip会员未添加

            }
            sm.setAcceptUsers(acceptUsers);

        }else {
            acceptUsers = sm.getAcceptUsers();
        }

        // 去掉null值
        acceptUsers.removeAll(Collections.singleton(null));//去掉集合中的空值

        for (String acceptUser:acceptUsers){
            SendMessage s = new SendMessage();
            BeanUtils.copyProperties(sm,s);
            s.setAcceptUser(acceptUser);
            s.setState(1);//设置未发送 TODO 利用定时任务，设置时间在执行发送
            sms.add(s);
        }
        boolean b = this.saveBatch(sms);

        return b;
    }


}
